package com.isolate.run;

import com.zaxxer.nuprocess.NuAbstractProcessHandler;
import com.zaxxer.nuprocess.NuProcess;
import lombok.extern.slf4j.Slf4j;

import java.nio.ByteBuffer;

@Slf4j
class ProcessHandler extends NuAbstractProcessHandler {

    private NuProcess nuProcess;

    private String content;

    public void setContent(String content) {
        this.content = content;
    }

    public ProcessHandler() {
        super();
    }

    @Override
    public void onPreStart(NuProcess nuProcess) {
        super.onPreStart(nuProcess);
    }

    @Override
    public void onExit(int statusCode) {
        super.onExit(statusCode);
    }

    @Override
    public void onStderr(ByteBuffer buffer, boolean closed) {
        byte[] bytes = new byte[buffer.remaining()];
        // You must update buffer.position() before returning (either implicitly,
        // like this, or explicitly) to indicate how many bytes your handler has consumed.
        buffer.get(bytes);
        System.out.println(new String(bytes));

        super.onStderr(buffer, closed);
    }

    @Override
    public void onStart(NuProcess nuProcess) {
        this.nuProcess = nuProcess;
    }

    @Override
    public boolean onStdinReady(ByteBuffer buffer) {
        log.info("content:[{}]", content);
        buffer.put(content.getBytes());
        buffer.flip();
        return false;
    }

    @Override
    public void onStdout(ByteBuffer buffer, boolean closed) {
        if (!closed) {
            byte[] bytes = new byte[buffer.remaining()];
            buffer.get(bytes);
            log.info("res:[{}]", new String(bytes));
        }
    }
}
